<template>
  <div>
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
    <!-- 加载更多 -->
    <van-list
  v-model="loading"
  :finished="finished"
  finished-text="没有更多了"
  @load="onLoad"
   offset="50"
    :immediate-check="false"
>
    <!-- 文章列表 -->
    <article-item
    v-for="(item,index) in articleList" :key="index"
    :obj='item'
    ></article-item>
    </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { articlesListAPI } from '@/api'
import ArticleItem from './components/ArticleItem.vue'
import { timeAgo } from '@/utils/date.js'
export default {
  data () {
    return {
      nextTime: null, // 用于加载更多(分页)
      articleList: [],
      loading: false, // 底部加载状态
      finished: false, // 数据是否全部加载完成
      isLoading: false
    }
  },
  props: {
    cid: Number
  },
  components: {
    ArticleItem
  },
  async created () {
    const res = await articlesListAPI({
      channel_id: this.cid
    })
    // this.articleList = res.data.data.results
    res.data.data.results.forEach((item) => {
      item.pubdate = timeAgo(item.pubdate)
    })
    console.log(this.articleList)
    this.getArticleList()
  },
  methods: {
    onLoad () {
      // 底部加载 获取数据的时候触发
      console.log('到底了')
      if (this.articleList.length > 0) {
        this.getArticleList()
      }
    },
    // 顶部刷新事件方法
    async onRefresh () {
      this.nextTime = null
      this.articleList = []
      await this.getArticleList()
      this.isLoading = false // 顶部加载状态关闭
    },
    async getArticleList () {
      // 负责拿文章列表数据
      const res = await articlesListAPI({
        channel_id: this.cid,
        timestamp: this.nextTime
      })
      console.log(res)
      // 回来的数据进行预处理, 把时间转成多久多久之前
      res.data.data.results.forEach((obj) => {
        obj.pubdate = timeAgo(obj.pubdate)
      })

      // 如果无数据
      if (res.data.data.results.length === 0) {
        this.finished = true // 告诉list组件直接底部显示没有更多数据
      } else {
        this.nextTime = res.data.data.pre_timestamp // 保存下一页数据的时间(做分页用)
        this.articleList = [...this.articleList, ...res.data.data.results]
        // 等待网络请求结果后
        this.loading = false // 底部加载更多状态
      }
    }
  }

}
</script>
